package com.igeek.web;

import com.google.gson.Gson;
import com.igeek.domain.Category;
import com.igeek.service.CategoryService;
import com.igeek.utils.JedisPoolUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jerryHe
 * @create 2019-10-08 15:59
 */

@WebServlet("/category")
public class CategoryServlet extends BaseServlet {



    public void getCategories(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //判断缓存中是否有分类数据，如果有直接从缓存中取，如果没有，从数据库中取
        //连接到redis
        //读取配置文件中的连接信息
        String gsonString="";
        Jedis jedis = null;
        try {
            jedis = JedisPoolUtils.getJedis();
        } catch (Exception e) {
            //1.调用service
            CategoryService service = new CategoryService();
            List<Category> categories = service.findAllCategories();
            //2.把数据转换成json格式
            Gson gson = new Gson();
            gsonString = gson.toJson(categories);
            System.out.println(gsonString);
            response.getWriter().write(gsonString);
            //e.printStackTrace();
            return;
        }
        //假设把分类信息存入redis (k,v) ,key category
        gsonString = jedis.get("category");
        if(gsonString== null){
            //1.调用service
            CategoryService service = new CategoryService();
            List<Category> categories = service.findAllCategories();
            //2.把数据转换成json格式
            Gson gson = new Gson();
            gsonString = gson.toJson(categories);
            System.out.println(gsonString);
            //把数据库中的分类数据存入redis
            jedis.set("category",gsonString);
        }
        //3.把数据发送到前台
        response.getWriter().write(gsonString);
    }
}
